package com.huitong.common.security.config;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.same.SaSameUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.huitong.common.core.constant.UserConstant;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import static org.springframework.http.HttpStatus.UNAUTHORIZED;

/**
 * 权限安全配置
 *
 * @author fromdrowning
 * @date 2024/3/20 9:37
 */
@AutoConfiguration
public class SecurityConfiguration implements WebMvcConfigurer {

    /**
     * 注册Sa-Token的拦截器
     *
     * @param registry 拦截器注册类
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册路由拦截器 自定义验证规则
        registry.addInterceptor(new SaInterceptor(handler -> {
                SaRouter.match("/student/**", r -> StpUtil.checkRole(UserConstant.STUDENT));
                SaRouter.match("/teacher/**", r -> StpUtil.checkRole(UserConstant.TEACHER));
                SaRouter.match("/admin/**", r -> StpUtil.checkRole(UserConstant.ADMIN));
            }))
            .addPathPatterns("/**");
    }

    /**
     * 配置过滤器 校验是否从网关转发
     *
     * @return 过滤器
     */
    @Bean
    public SaServletFilter saServletFilterCustomizer() {
        return new SaServletFilter().addInclude("/**")
            .setAuth(obj -> {
                if (SaManager.getConfig().getCheckSameToken()) {
                    SaSameUtil.checkCurrentRequestToken();
                }
            })
            .setError(e -> SaResult.error("认证失败 无法访问系统资源")
                .setCode(UNAUTHORIZED.value()));
    }
}
